import { observable, action, toJS } from 'mobx';
import { Bubble, Tools } from 'weaver-mobile';
import { Form, Upload } from 'weaver-mobile-page';
import { FormatDate } from '../util';
import * as Api from '../apis';

const getLabel = Tools.getLabel;
const initalState = {
  newGroupVoteLoading: true,
  voteOptions: {
    1: { key: 1, imageArr: [] },
    2: { key: 2, imageArr: [] },
  },
  optionFormsMap: {},
  optCondition: {},
  themeImages: [],
  publishLoading: false,
}
export default class NewGroupVoteStore {
  @observable newVoteForm = new Form.Store({ route: '/groupVote/new' });
  @observable themeUpload = new Upload.Store({ route: '/groupVote/new' });
  @observable newGroupVoteLoading = initalState.newGroupVoteLoading;
  @observable themeImages = initalState.themeImages;
  @observable voteOptions = initalState.voteOptions;
  @observable optionFormsMap = initalState.optionFormsMap;
  @observable optCondition = initalState.optCondition;
  @observable publishLoading = initalState.publishLoading;

  @action setStoreState = (params, callback) => {
    Object.keys(params).forEach(key => {
      this[key] = params[key];
    });
    if (callback) callback();
  }

  @action clear = () => this.setStoreState(initalState)

  // 发起新投票
  @action initiateVote = async () => {
    this.newGroupVoteLoading = true;
    this.optCondition = await Api.groupvoteoptioncondition();
    if (this.optCondition) {
      this.changeOption();
      Api.groupvoteaddcondition().then(res => {
        if (res.conditioninfo) {
          let nextDay = FormatDate(new Date(new Date().getTime() + 24*60*60*1000), 'yyyy-MM-dd HH:mm:ss');
          this.newVoteForm.initForm(res.conditioninfo, '/groupVote/new');
          this.newVoteForm.updateField('voteendtime', nextDay)
        }
        this.newGroupVoteLoading = false;
      });
    }
  }

  @action changeOption = (data) => {
    Object.keys(toJS(this.voteOptions)).forEach(key => {
      if (!this.optionFormsMap[key]) {
        this.optionFormsMap[key] = new Form.Store({ route: '/groupVote/new' });
        this.optionFormsMap[key].initForm(this.optCondition.conditioninfo, '/groupVote/new');
      }
    })
  }

  /* 删除选项 */
  @action deleteOption = (key) => {
    let newOptions = toJS(this.voteOptions);
    delete newOptions[key];
    this.voteOptions = newOptions;
    if (this.optionFormsMap[key]) { // 重置表单数据
      this.optionFormsMap[key].resetFields();
    }
  }

  /* 表单验证 */
  validateForm = () => {
    const { voteendtime, checkmode, maxvoteoption } = this.newVoteForm.formParams;
    const optionsArr = Object.keys(toJS(this.voteOptions));
    const validateCheckmode = new Promise((resolve) => {
      if (checkmode === '1' && (!maxvoteoption || Number.isNaN(Number(maxvoteoption)) || Number(maxvoteoption) < 0)) {
        Bubble.error(getLabel('516197','请填写最多可选项数'));
      } else if (optionsArr.length < Number(maxvoteoption)) {
        Bubble.error(getLabel('516749','最多可选项数不能超过选项个数'));
      } else {
        resolve();
      }
    })
    // 投票选项校验
    const validateOptions = new Promise((resolve) => {
      let optionFlag = 0;
      optionsArr.forEach(key => {
        let valOpsForm = this.optionFormsMap[key].doValidate();
        if (!valOpsForm.pass) {
          Bubble.error(getLabel('516174','投票选项未填写'));
        } else {
          optionFlag++;
        }
      })
      if (optionFlag === optionsArr.length) {
        resolve();
      }
    })
    // 截止时间校验
    const validateEndTime = new Promise((resolve) => {
      if (!voteendtime) {
        Bubble.error(getLabel('516198','截止时间不能为空'));
      } else if (voteendtime) {
        resolve();
      }
    })
    return Promise.all([validateCheckmode, validateOptions, validateEndTime]); 
  }

  /* 表单参数 */
  setParams = () => {
    let newVoteParams = this.newVoteForm.formParams;
    let opsVoteParams = [];
    Object.keys(toJS(this.voteOptions)).forEach(key => {
      let valOpsForm = this.optionFormsMap[key].formParams;
      let optcontent = valOpsForm.optionContent;
      let optfileids = valOpsForm.optionImage;
      opsVoteParams = [...opsVoteParams, {optcontent, optfileids}]
    });

    return {
      ...newVoteParams,
      groupvotename: newVoteParams.groupvotename.trim(),
      voteoption: JSON.stringify(opsVoteParams),
      optioncount: opsVoteParams.length,
      finishTime: newVoteParams.voteendtime,
      enddate: newVoteParams.voteendtime.split(' ')[0],
      endtime: newVoteParams.voteendtime.split(' ')[1],
    }
  }

  /* 发布投票 */
  @action publishVote = (params, successCallBack) => {
    let valForm = this.newVoteForm.doValidate();
    if (valForm.pass) {
      this.validateForm().then(() => {
        this.publishLoading = true;
        let formParams = this.setParams();
        params = {...formParams, ...params};
        Api.groupchatvoteadd(params).then(res => {
          if (res.api_status === 'success') {
            Bubble.success(getLabel('513696','发布成功!') );
            if (typeof(successCallBack) === 'function') successCallBack(res);
          } else {
            Bubble.error(getLabel('516191','发布失败，请重试！'))
          }
          this.publishLoading = false;
        })
      })
    }
  }
}